package com.zlyx.easy.swagger.scanner;

import java.util.List;

import org.apache.maven.model.Developer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

import com.zlyx.easy.core.event.IHandlerOnRefreshed;
import com.zlyx.easy.core.list.Lists;
import com.zlyx.easy.core.tool.EasyBuffer;
import com.zlyx.easy.core.tool.Ops;
import com.zlyx.easy.swagger.config.ApiConfiguration;
import com.zlyx.easy.swagger.config.ApiConfiguration.ApiProperties;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @Auth 赵光
 * @Describle
 * @2019年6月23日 下午10:02:31
 */
public abstract class AbstractSwaggerScanner implements IHandlerOnRefreshed {

	protected DefaultListableBeanFactory listableBeanFactory;

	@Autowired
	protected ApiConfiguration apiConfiguration;

	@Autowired
	protected DocumentationCache documentationCache;

	/**
	 * 在当前服务中注册子模块的Docket
	 * 
	 * @param properties
	 */
	public void registerDocket(String groupName, ApiProperties properties) {
		if (listableBeanFactory.containsBean(groupName)) {
			groupName = EasyBuffer.newString(groupName, "@", properties.hashCode());
		}
		listableBeanFactory.registerSingleton(groupName, createDocket(properties));
	}

	public Docket createDocket(ApiProperties properties) {
		return new Docket(DocumentationType.SWAGGER_2).groupName(properties.getGroupName()).enable(false)
				.additionalModels(ApiConfiguration.getDefaultResolvedType(), ApiConfiguration.getModels())
				.apiInfo(createApiInfo(properties)).select().paths(PathSelectors.ant(properties.getGroupPath()))
				.apis(RequestHandlerSelectors.basePackage(properties.getGroupPackage())).build();
	}

	public ApiInfo createApiInfo(ApiProperties properties) {
		List<String> developers = Lists.newList();
		List<String> emails = Lists.newList();
		if (!properties.getDevelopers().isEmpty()) {
			List<Developer> developerList = properties.getDevelopers();
			for (Developer developer : developerList) {
				developers.add(developer.getName());
				emails.add(developer.getEmail());
			}
		}
		return new ApiInfoBuilder().title(Ops.getValue(properties.getTitle(), properties.getGroupName()))
				.description(properties.getDescription()).termsOfServiceUrl(apiConfiguration.getUrl())
				.version(apiConfiguration.getVersion()).contact(new Contact(Ops.toString(developers, ", "),
						apiConfiguration.getUrl(), Ops.toString(emails, ", ")))
				.build();
	}
}
